<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <el-tabs>
          <!-- 放置页签 -->
          <el-tab-pane label="角色管理">
            <!-- 新增角色按钮 -->
            <el-row style="height: 60px">
              <el-button
                icon="el-icon-plus"
                size="small"
                type="primary"
                @click="hAdd"
              >新增角色</el-button>
            </el-row>
            <!-- 表格 -->
            <el-table :data="list">
              <el-table-column label="序号" width="120" type="index" />
              <el-table-column label="角色名称" width="240" prop="name" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label="操作">
                <template #default="{ row }">
                  <el-button size="small" type="success" @click="hAssignPer(row.id)">分配权限</el-button>
                  <el-button
                    size="small"
                    type="primary"
                    @click="hEdit(row)"
                  >编辑</el-button>
                  <el-button
                    size="small"
                    type="danger"
                    @click="hDel(row.id)"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <el-row
              type="flex"
              justify="center"
              align="middle"
              style="height: 60px"
            >
              <!-- 分页组件 -->
              <el-pagination
                :current-page="pageParams.page"
                :page-sizes="[2, 4, 5, 6, 8]"
                :page-size="pageParams.pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-card>
      <!-- 准备一个新的弹层 -->
      <el-dialog title="新增角色" :visible.sync="showDialog" @close="hClose">
        <el-form
          ref="roleForm"
          :model="roleForm"
          :rules="rules"
          label-width="100px"
        >
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="roleForm.name" />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="roleForm.description" />
          </el-form-item>
        </el-form>
        <!-- 底部 -->
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button size="small">取消</el-button>
            <el-button
              size="small"
              type="primary"
              @click="hSubmit"
            >确定</el-button>
          </el-col>
        </el-row>
      </el-dialog>
      <!-- 分配权限弹层 -->
      <el-dialog title="分配权限" :visible.sync="perShowDialog">
        <assignPer v-if="perShowDialog" :role-id="roleId" @success="perShowDialog = false" />
      </el-dialog>
    </div>
  </div>
</template>
<script>
import assignPer from './assignPermission.vue'
import { getRoles, addRoles, editRoles, deleteRoles } from '@/api/settings'
export default {
  components: { assignPer },
  data() {
    return {
      // 表单需要的数据
      roleForm: {
        name: '',
        description: ''
      },
      // 表单校验规则
      rules: {
        name: [
          { required: true, message: '请您输入角色名称', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请您输入角色描述', trigger: 'blur' }
        ]
      },
      list: [],
      pageParams: {
        page: 1,
        pagesize: 10
      },
      total: 0,
      showDialog: false,
      isEdit: false,
      perShowDialog: false,
      roleId: ''
    }
  },
  created() {
    this.loadRoles()
  },
  methods: {
    hAssignPer(id) {
      this.perShowDialog = true
      this.roleId = id
    },
    // 重置表单
    hClose() {
      // 初始化
      this.$refs.roleForm.resetFields()
      //  手动清空表单
      this.roleForm = {
        name: '',
        description: ''
      }
    },
    // 点击确认按钮
    hSubmit() {
      this.$refs.roleForm.validate((valid) => {
        // 兜底校验不通过
        if (!valid) return
        // 兜底校验通过
        this.isEdit ? this.doEdit() : this.doAdd()
      })
    },
    hAdd() {
      this.isEdit = false
      this.showDialog = true
    },
    // 添加角色
    async doAdd() {
      try {
        const res = await addRoles(this.roleForm)
        console.log(res, 'addRoles')
        this.total++
        const maxPage = Math.ceil(this.total / this.pageParams.pagesize)
        this.pageParams.page = maxPage
        // 刷新页面
        this.loadRoles()
        // 关闭弹层
        this.showDialog = false
      } catch (error) {
        console.log(error)
      }
    },
    // 编辑功能
    hEdit(row) {
      console.log(row, 'row')
      this.isEdit = true
      // 表单数据双向绑定，使用浅拷贝解决
      this.roleForm = { ...row }
      this.showDialog = true
    },
    // 实现编辑功能
    async doEdit() {
      try {
        const res = await editRoles(this.roleForm)
        console.log(res, 'editRoles')
        // 刷新列表
        this.loadRoles()
        // 关闭弹层
        this.showDialog = false
      } catch (error) {
        console.log(error)
      }
    },
    // 删除功能
    hDel(id) {
      this.$confirm('您确认要删除该角色嘛？')
        .then(async() => {
          const res = await deleteRoles(id)
          // 优化判断数据是否为1条
          if (this.list.length === 1) {
            this.pageParams.page--
            if (this.pageParams.page <= 0) {
              this.pageParams.page = 1
            }
          }
          console.log(res, 'deleteRoles')
          if (res.data.code === 10000) {
            this.loadRoles()
          }
        })
        .catch((error) => {
          console.log(error)
        })
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.pageParams.page = 1
      this.pageParams.pagesize = val
      this.loadRoles()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.pageParams.page = val
      this.loadRoles()
    },
    async loadRoles() {
      try {
        const res = await getRoles(this.pageParams)
        console.log(res, 'getRoles')
        this.list = res.data.data.rows
        this.total = res.data.data.total
      } catch (error) {
        this.$message.error('获取角色信息失败')
      }
    }
  }
}
</script>
